//
//  ZLComposeTypeView.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 17/1/4.
//  Copyright © 2017年 hanju001. All rights reserved.
//

import UIKit
import pop

//撰写微博类型视图
class ZLComposeTypeView: UIView {

    @IBOutlet weak var scrollView: UIScrollView!
    
    @IBOutlet weak var returnButton: UIButton!
    
    @IBOutlet weak var closeButtonCenterX: NSLayoutConstraint!
    
    @IBOutlet weak var returnButtonCenterX: NSLayoutConstraint!
    fileprivate let buttonInfos = [["imageName":"tabbar_compose_idea","title":"文字","clsName":"ZLComposeViewController"],
                       ["imageName":"tabbar_compose_photo","title":"图片/视频"],
                       ["imageName":"tabbar_compose_weibo","title":"长微博"],
                       ["imageName":"tabbar_compose_lbs","title":"签到"],
                       ["imageName":"tabbar_compose_review","title":"点评"],
                       ["imageName":"tabbar_compose_more","title":"更多","actionName":"clickMore"],
                       ["imageName":"tabbar_compose_friend","title":"朋友圈"],
                       ["imageName":"tabbar_compose_wbcamera","title":"微博相机"],
                       ["imageName":"tabbar_compose_music","title":"音乐"],
                       ["imageName":"tabbar_compose_shooting","title":"拍摄"]]
    
    fileprivate var completionBlock: ((_ clsName: String?)->())?
    class func composeType() -> ZLComposeTypeView {
        
        let nib = UINib(nibName: "ZLComposeTypeView", bundle: nil)
        let v = nib.instantiate(withOwner: nil, options: nil)[0] as! ZLComposeTypeView
        
        v.frame = UIScreen.main.bounds
        
        v.setupUI()
        
        return v
    }

    func show(completion: @escaping (_ clsName: String?)->()) {
        
        //记录闭包，需要的时候执行
        completionBlock = completion
        guard let vc = UIApplication.shared.keyWindow?.rootViewController else{
            
            return
        }
        //添加到跟视图的控制器
        vc.view.addSubview(self)
        
        //设置动画
        showCurrentView()
    }
    
    @objc fileprivate func clickButton(button: ZLComposeTypeButton) {
        
        print("\(clickButton)")
        //根据contentoffset判断当前显示的子视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        
        //选中的按钮的放大其它的按钮缩小
        for (i, btn) in v.subviews.enumerated() {
         
            let scaleAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewScaleXY)
            let scale = (button == btn) ? 1.5 : 0.5
            let value = NSValue(cgPoint: CGPoint(x: scale, y: scale))
            scaleAnim.toValue = value
            scaleAnim.duration = 0.5
            btn.pop_add(scaleAnim, forKey: nil)
            
            //渐变动画  动画组
            let alphaAnim: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
            
            alphaAnim.toValue = 0.2
            alphaAnim.duration = 0.5
            
            btn.pop_add(alphaAnim, forKey: nil)
            //监听动画
            if i == 0 {
                alphaAnim.completionBlock = {(_, _)->() in
                    
                    //需要执行回调 完成的闭包
                    self.completionBlock?(button.clsName)
                }
            }
        }
        
    }
    @objc fileprivate func clickMore(){
        print("\(clickMore)")
        //滚动到第二页
        
        handleBottomButton(isLeft: false)
        
    }
    
    @IBAction func clickReturn(_ sender: Any) {
        
        handleBottomButton(isLeft: true)
        
    }
    fileprivate func handleBottomButton(isLeft: Bool) {
        
        let offsetX = isLeft ? 0 : scrollView.bounds.width
        scrollView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: true)
        //处理底部按钮
        
        
        let margin = scrollView.bounds.width / 6
        closeButtonCenterX.constant += isLeft ? (-margin) : margin
        returnButtonCenterX.constant -= isLeft ? (-margin) : margin
        UIView.animate(withDuration: 0.25, animations: { 
            
            self.layoutIfNeeded()
            
            self.returnButton.alpha = 0
        }) { (_) in
            
            self.returnButton.isHidden = isLeft
            self.returnButton.alpha = 1
        }
        
    }
    @IBAction func close() {
        
        //影藏button动画
        hideButtons()
        
    }
    
}
// MARK --- 动画方法扩展
private extension ZLComposeTypeView {
   
    func showCurrentView() {
         //创建动画
        let anim = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        anim?.fromValue = 0
        anim?.toValue = 1
        anim?.duration = 0.25
        
        pop_add(anim, forKey: nil)
        //按钮的弹力动画
        showButtons()
    }
    
    /// 弹力显示所有的按钮
    func showButtons() {
        //获取scrollView子视图
        let v = scrollView.subviews[0]
        
        for (i, btn) in v.subviews.enumerated(){
            
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y + 350
            anim.toValue = btn.center.y
            anim.springBounciness = 8
            anim.springSpeed = 8
            //设置动画启动时间
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(i) * 0.025
            btn.pop_add(anim, forKey: nil)
        }
    }
    /// 隐藏动画
    func hideButtons() {
        
        //根据contentoffset判断当前显示的子视图
        let page = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        let v = scrollView.subviews[page]
        for (i, btn) in v.subviews.enumerated().reversed() {
            
            let anim: POPSpringAnimation = POPSpringAnimation(propertyNamed: kPOPLayerPositionY)
            anim.fromValue = btn.center.y
            anim.toValue = btn.center.y + 350
            
            anim.beginTime = CACurrentMediaTime() + CFTimeInterval(v.subviews.count - i) * 0.025
            btn.pop_add(anim, forKey: nil)
            if i == 0 {
                
                anim.completionBlock = {(_, _)->() in
                    
                    self.hideCurrentView()
                }
            }
        }
        
        
    }
    
    //隐藏当前视图
    func hideCurrentView() {
        let animi: POPBasicAnimation = POPBasicAnimation(propertyNamed: kPOPViewAlpha)
        animi.fromValue = 1
        animi.toValue = 0
        animi.duration = 0.15
        
        pop_add(animi, forKey: nil)
        
        animi.completionBlock = {(_, _)->() in
            
            self.removeFromSuperview()
        }
    }
    
}

private extension ZLComposeTypeView {
    
    func setupUI() {
        
        //强行更新布局
        layoutIfNeeded()
        
        //添加视图
        let rect = scrollView.bounds
        let width = scrollView.bounds.width
        for i in 0..<2 {
            
            let v = UIView(frame: rect.offsetBy(dx: CGFloat(i) * width, dy: 0))
 
            //添加按钮
            addButtons(v: v, idx: i * 6)
            
            scrollView.addSubview(v)
        }
        //设置scrollView
        scrollView.contentSize = CGSize(width: 2 * rect.width, height: rect.height)
        scrollView.showsVerticalScrollIndicator = false
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.bounces = false
        scrollView.isPagingEnabled = false
        //禁用滚动
        scrollView.isScrollEnabled = false
        
    }
    func addButtons(v: UIView, idx: Int) {
        
        //从idex添加6个按钮
        let count = 6
        for i in idx..<(idx + count){
            
            //从数组字典中获取图像名称和title
            
            if i >= buttonInfos.count{
                
                break
            }
            let dict = buttonInfos[i]
            guard let imageName = dict["imageName"],let title = dict["title"] else {
                
                continue
            }
            
            let btn = ZLComposeTypeButton.composeTypeButton(imageName: imageName, title: title)
            
            //添加到视图
            v.addSubview(btn)
            if let actinName = dict["actionName"] {
                
                btn.addTarget(self, action: Selector(actinName), for: .touchUpInside)
            }else{
                
                btn.addTarget(self, action: #selector(clickButton(button:)), for: .touchUpInside)
            }
            //设置要展现的类名 注意不需要任何守护判断
            btn.clsName = dict["clsName"]
            
        }
        //布局按钮
        //准备常量
        let btnSize = CGSize(width: 100, height: 100)
        let margin = (v.bounds.width - 3 * btnSize.width) / 4.0
        for (i, btn) in v.subviews.enumerated()
        {
            let y = (i > 2) ? (v.bounds.height - btnSize.height) : 0
            let col = i % 3
            let x = CGFloat(col + 1) * margin + CGFloat(col) * btnSize.width
            btn.frame = CGRect(x: x, y: CGFloat(y), width: btnSize.width, height: btnSize.height)
            
        }
        
    }
}
